package by.bucha.testproject.fragments;

import java.io.File;
import java.sql.Date;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import by.bucha.testproject.R;
import by.bucha.testproject.adapters.FileArrayAdapter;
import by.bucha.testproject.content.bo.fileExplorer.FileExplorerListItemModel;
import by.bucha.testproject.imageLoader.ExternalFileCache;

import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

public class FileExplorerFragment extends ListFragment implements
		OnScrollListener {

	private String mCurrentDir;

	private FileArrayAdapter mAdapter;

	public static boolean sBusy = false;

	public static final String ANDROID_IMAGE_FORMATS = ".jpg .gif .png .bmp";

	public static final String ANDROID_API14_AND_HIGHER_IMAGE_FORMATS = ".jpg .gif .png .bmp .webp";

	private String mParentDirectoryName = "sdcard";

	private String mExtraCurrentDirr = "string to save current dirr";

	public FileExplorerFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			String currentDirr = savedInstanceState
					.getString(mExtraCurrentDirr);
			if (currentDirr == null) {
				mCurrentDir = Environment.getExternalStorageDirectory()
						.getPath();
			} else {
				mCurrentDir = currentDirr;
			}
		} else {
			mCurrentDir = Environment.getExternalStorageDirectory().getPath();
		}
		process(mCurrentDir);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(mExtraCurrentDirr, mCurrentDir);
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getListView().setOnScrollListener(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		sBusy = false;
	}

	private void process(String fileName) {
		File file = new File(fileName);
		File[] filesWithDirs = file.listFiles();

		String title = getActivity().getApplicationContext().getResources()
				.getString(R.string.file_explorer_fragment_strings_dirs_title);

		getActivity().setTitle(title + file.getAbsolutePath());

		List<FileExplorerListItemModel> dirList = new ArrayList<FileExplorerListItemModel>();
		List<FileExplorerListItemModel> filesList = new ArrayList<FileExplorerListItemModel>();

		try {

			for (File currentFile : filesWithDirs) {

				Date lastModifiedDate = new Date(currentFile.lastModified());

				DateFormat formater = DateFormat.getDateTimeInstance();

				String modifiedDate = formater.format(lastModifiedDate);

				if (currentFile.isDirectory()) {

					File[] fileBuffer = currentFile.listFiles();

					int bufferSize = 0;

					if (fileBuffer != null) {
						bufferSize = fileBuffer.length;
					}

					String itemsNumber = String.valueOf(bufferSize);

					if (bufferSize == 0) {
						String item = getActivity()
								.getApplicationContext()
								.getResources()
								.getString(
										R.string.file_explorer_fragment_strings_item);

						itemsNumber = itemsNumber + item;

					} else {
						String items = getActivity()
								.getApplicationContext()
								.getResources()
								.getString(
										R.string.file_explorer_fragment_strings_items);

						itemsNumber = itemsNumber + items;
					}

					dirList.add(new FileExplorerListItemModel(currentFile
							.getName(), itemsNumber, modifiedDate, currentFile
							.getAbsolutePath(), true, false, false));
				} else {
					String byteString = getActivity()
							.getApplicationContext()
							.getResources()
							.getString(
									R.string.file_explorer_fragment_strings_byte);

					if (android.os.Build.VERSION.SDK_INT >= 14) {

						if (isImage(currentFile,
								ANDROID_API14_AND_HIGHER_IMAGE_FORMATS)) {

							filesList.add(new FileExplorerListItemModel(
									currentFile.getName(), currentFile.length()
											+ byteString, modifiedDate,
									currentFile.getAbsolutePath(), false,
									false, true));
						}
					} else {
						if (isImage(currentFile, ANDROID_IMAGE_FORMATS)) {

							filesList.add(new FileExplorerListItemModel(
									currentFile.getName(), currentFile.length()
											+ byteString, modifiedDate,
									currentFile.getAbsolutePath(), false,
									false, true));
						}
					}
				}
			}
		} catch (Exception e) {

			String warning = getActivity()
					.getApplicationContext()
					.getResources()
					.getString(
							R.string.file_explorer_fragment_strings_errore_by_opening_dirr);

			Toast.makeText(getActivity().getApplicationContext(),
					warning + e.getMessage(), Toast.LENGTH_SHORT).show();
		}

		Collections.sort(dirList);
		Collections.sort(filesList);

		dirList.addAll(filesList);

		if (!file.getName().equalsIgnoreCase(mParentDirectoryName)) {

			String parentString = getActivity().getApplicationContext()
					.getResources()
					.getString(R.string.file_explorer_fragment_strings_parent);

			dirList.add(0, new FileExplorerListItemModel("..", parentString,
					"", file.getParent(), false, true, false));

		}

		mAdapter = new FileArrayAdapter(getActivity().getApplicationContext(),
				R.layout.view_fragment_file_explorer, dirList);

		this.setListAdapter(mAdapter);
	}

	@Override
	public void onListItemClick(ListView list, View view, int position, long id) {

		super.onListItemClick(list, view, position, id);

		FileExplorerListItemModel model = mAdapter.getItem(position);

		if (model.isFolder() || model.isBack()) {

			mCurrentDir = model.getPath();
			process(mCurrentDir);

		} else {
			try {
				ExternalFileCache.getInstance().put(model.getPath());
			} catch (Exception e) {

				Toast.makeText(getActivity().getApplicationContext(),
						e.getMessage(), Toast.LENGTH_SHORT).show();
			}
			String notification = getActivity().getApplicationContext()
					.getResources()
					.getString(R.string.file_explorer_fragment_strings_added);

			Toast.makeText(getActivity().getApplicationContext(), notification,
					Toast.LENGTH_SHORT).show();
		}
	}

	private Boolean isImage(File file, String formats) {
		int idx = file.getName().lastIndexOf('.');
		if (idx > 0) {
			String currentFormat = file.getName().substring(idx);
			if (formats.contains(currentFormat.toLowerCase())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_IDLE:
			sBusy = false;
			int count = view.getChildCount();

			Boolean isNotifyed = false;

			for (int i = 0; i < count; i++) {
				if (view.getChildAt(i).getTag() != null && isNotifyed == false) {
					isNotifyed = true;
					mAdapter.notifyDataSetChanged();
				}
				view.getChildAt(i).setTag(null);
			}
			break;
		case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

			sBusy = false;
			break;
		case OnScrollListener.SCROLL_STATE_FLING:

			sBusy = true;
			break;
		}
	}
}
